//
//  SYDrawViewController.m
//  SanYiTeaching
//
//  Created by 陈豪 on 2020/4/28.
//  Copyright © 2020 SanYi. All rights reserved.
//

#import "SYDrawViewController.h"
#import "ZYQAssetPickerController.h"
#import "UIView+WHB.h"
#import "HBDrawingBoard.h"
#import "MJExtension.h"
#import "SYBaiBanFuDaoViewController.h"
#import "SYPlayerEditViewController.h"//视频编辑
#import "UIImage+SY.h"
#import "SYPlayerViewController.h"
#import "SYCollectionViewController.h"
#import "SYPPTViewController.h"
#import "SYChooseImageViewController.h"

@interface SYDrawViewController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,HBDrawingBoardDelegate>

@property (nonatomic, strong) HBDrawingBoard *drawView;
@property (weak, nonatomic) IBOutlet UIView *drewBackView;
@property (nonatomic, strong) UIView *videoView;
@property (strong, nonatomic) SYBaiBanFuDaoViewController *interactionVC;

@property (strong, nonatomic) NSMutableArray *pointArr;


@property (strong, nonatomic) NSDictionary *WeiDIc;


@property (strong, nonatomic) NSString *imgaePath;

@property (strong, nonatomic) NSString *resourceId;

@property (assign, nonatomic) NSInteger nowIndex;

@property (strong, nonatomic) SYPlayerEditViewController *playerVC;



@end

@implementation SYDrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view addSubview:self.drawView];
    
    [self saveWeiKeRequestWithImagePath:@""];
    
    self.pointArr = [NSMutableArray array];
    
        // 这个录制视频入口
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionLongPress:)];
    //         最短长按时间
            longPress.minimumPressDuration = 1;
    [self.view addGestureRecognizer:longPress];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(faSongLuPing:) name:@"newWeiKeLuZhi" object:nil];
    
}
- (void)faSongLuPing:(NSNotification *)info{
    //微课视频录制成功之后接收到推送，返回一个task_id.
    NSString *pathFiel = [info.userInfo objectForKey:@"path"];
    NSMutableDictionary *dic = (NSMutableDictionary *)self.pointArr[self.nowIndex];
    [dic setValue:pathFiel forKey:@"taskId"];

    NSLog(@"%@",pathFiel);
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
//    [self drawSetting:nil];
}
- (IBAction)drawSetting:(id)sender {
    // 画板设置
    self.drawView.shapType = ((UIButton *)sender).tag;
    
    [self.drawView showSettingBoard];
}
- (IBAction)saveImage:(id)sender {
    
    [self.drawView hideSettingBoard];
    //  得到截图
//    UIImageWriteToSavedPhotosAlbum([self.drawView screenshot:self.drawView], nil, nil, nil);
    
       UIImage *newImage = [self.drawView screenshot:self.drawView];
    
        [self updataImageRequestWithImage:newImage];


}
- (IBAction)luZhiVideo:(id)sender {
    
    /*
    // 这个录制视频入口
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionLongPress:)];
         最短长按时间
        longPress.minimumPressDuration = 1;

    self.videoView = [[UIView alloc]initWithFrame:CGRectMake(0, 70, kScreen_WIDTH, kScreen_HEIGHT -70)];
    self.videoView.backgroundColor = [UIColor redColor];
    [self.videoView addGestureRecognizer:longPress];

    [self.view addSubview:self.videoView];
    
    */

    
//    [self weiKeLuPing];
    
}
- (void)weiKeLuPing {
    
    [SYRequestAPI bb_TutorServiceImInfoToken:Token success:^(id  _Nonnull dataList) {
        //这里需要房间号，名字，登录账号（生成的）
        [MBProgressHUD mj_hideHUDForView:self.view];
        self->_interactionVC = [[SYBaiBanFuDaoViewController alloc] init];
        
        //TOP 先写死
        //                SaveDataToNSUserDefaults([dataList nilObjectForKey:@"imId"], @"independence_ios");
        self->_interactionVC.userName = [dataList nilObjectForKey:@"imId"];
        self->_interactionVC.userSig = [dataList nilObjectForKey:@"userSig"];
        //NSInteger room = arc4random() %100;
        self->_interactionVC.newWeiKe = YES;
        self->_interactionVC.isChat = YES;
//        self->_interactionVC.isWeiKe = YES;
        NSString *roomId = [NSString stringWithFormat:@"9%@",GetDataFromNSUserDefaults(AcountIDDefalut)];
        
        self->_interactionVC.roomId = roomId;//SJStringWithFormat(room);
        self->_interactionVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:self->_interactionVC animated:YES completion:nil];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [MBProgressHUD zr_showError:error.domain];
        //            YLSLog(@"----请求错误");
    }];
}


-(void)actionLongPress:(UILongPressGestureRecognizer*)longPress{
    // 根据手势的状态判断，只有第一次执行时是UIGestureRecognizerStateBegan，其余都是UIGestureRecognizerStateEnd状态。
    
        if (longPress.state == UIGestureRecognizerStateBegan) {
            
        // 长按 换张图片
        // 获取到长按的view
            NSLog(@"window:%f,y:%f",kScreen_WIDTH,kScreen_HEIGHT);

            CGPoint point = [longPress locationInView:self.videoView];
            NSLog(@"handleSingleTap!pointx:%f,y:%f",point.x,point.y);
            NSString *Xpoint = [NSString stringWithFormat:@"%.3f",point.x];
            NSString *Ypoint = [NSString stringWithFormat:@"%.3f",(point.y -70)];
            NSArray *floorList = self.WeiDIc[@"listFloor"];
            NSDictionary *floorDic = floorList[0];
            NSString *floorId = [NSString stringWithFormat:@"%@",[floorDic nilObjectForKey:@"id"]];
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            
            [dic setValue:Xpoint forKey:@"x"];
            [dic setValue:Ypoint forKey:@"y"];
            [dic setValue:@"0" forKey:@"isCreat"];
            [dic setValue:@"" forKey:@"taskId"];
            [dic setValue:@"" forKey:@"video"];

            [dic setValue:floorId forKey:@"floorId"];

            [self.pointArr addObject:dic];
            [self CreatBtnForVideo];
        }

}
//  开始创建button
-(void)CreatBtnForVideo{
        for (int p = 0; p < self.pointArr.count; p ++) {
        NSMutableDictionary *muDic = (NSMutableDictionary *)self.pointArr[p];
        
        if ([[NSString stringWithFormat:@"%@",[muDic nilObjectForKey:@"isCreat"]] isEqualToString:@"0"]) {
            UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
            
            if (orientation == UIInterfaceOrientationLandscapeRight) {
                
                UIButton *btn = [[UIButton alloc]init];
                btn.center = CGPointMake( [[muDic nilObjectForKey:@"y"] floatValue]+70,self.view.height -[[muDic nilObjectForKey:@"x"] floatValue]);
                                        
                btn.bounds = CGRectMake(0, 0, 50, 50);
                btn.tag = 1000 + p;
                            //            btn.backgroundColor = [UIColor redColor];
                [btn setImage:[UIImage imageNamed:@"deaw_video"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(lookVideoBtnCliick:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:btn];
                
            }else if (orientation == UIInterfaceOrientationLandscapeLeft){
                
                UIButton *btn = [[UIButton alloc]init];
                btn.center = CGPointMake(self.view.width - [[muDic nilObjectForKey:@"y"] floatValue]-70,[[muDic nilObjectForKey:@"x"] floatValue]);
                            
                btn.bounds = CGRectMake(0, 0, 50, 50);
                btn.tag = 1000 + p;
                //            btn.backgroundColor = [UIColor redColor];
                [btn setImage:[UIImage imageNamed:@"deaw_video"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(lookVideoBtnCliick:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:btn];
            }

            [muDic setValue:@"1" forKey:@"isCreat"];
        }
    }
}


-(void)lookVideoBtnCliick:(UIButton *)sender{
    NSInteger index = sender.tag - 1000;
    
    self.nowIndex = index;
    
    NSMutableDictionary *dic = (NSMutableDictionary *)self.pointArr[index];
    
    if ([NSString stringWithFormat:@"%@",dic[@"taskId"]].length <= 0) {
        
        [self weiKeLuPing];
        
    }else{
        if ([NSString stringWithFormat:@"%@",dic[@"video"]].length <= 0) {
            
            __weak typeof(self) weakSelf = self;
            _playerVC = [[SYPlayerEditViewController alloc] init];
            
            _playerVC.taskId = [NSString stringWithFormat:@"%@",dic[@"taskId"]];
            
            _playerVC.backVideoPath = ^(NSDictionary * _Nonnull pathDic) {
                
                [dic setValue:pathDic[@"RelativePath"] forKey:@"video"];
                [dic setValue:pathDic[@"RemotePath"] forKey:@"videoStr"];
                [dic setValue:[NSString stringWithFormat:@"%@",pathDic[@"Duration"]] forKey:@"Duration"];
                [dic setValue:[NSString stringWithFormat:@"%@",pathDic[@"Size"]] forKey:@"Size"];

                [weakSelf uploadVideoPathWithVideoDic:dic];
            };
            [self.navigationController pushViewController:_playerVC animated:YES];
            
            return;
            
        }

        SYPPTViewController *playerVC = [[SYPPTViewController alloc] init];
        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        playerVC.urlStr = [NSString stringWithFormat:@"%@",dic[@"videoStr"]];
        [self presentViewController:playerVC animated:YES completion:nil];
        
        //显示弹出框列表选择
//        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
//                                                                       message:@""
//                                                                preferredStyle:UIAlertControllerStyleActionSheet];
//        alert.popoverPresentationController.sourceView = self.view;
//        alert.popoverPresentationController.sourceRect = CGRectMake(0,0,self.view.width - [[dic nilObjectForKey:@"y"] floatValue]-60,self.view.height -[[dic nilObjectForKey:@"x"] floatValue]+10);
//
//        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
//                                                              handler:^(UIAlertAction * action) {
//                                                                  //响应事件
//                                                                  NSLog(@"action = %@", action);
//                                                              }];
////        UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"重新编辑" style:UIAlertActionStyleDestructive
////                                                             handler:^(UIAlertAction * action) {
////            __weak typeof(self) weakSelf = self;
////            self->_playerVC = [[SYPlayerEditViewController alloc] init];
////
////            self->_playerVC.taskId = [NSString stringWithFormat:@"%@",dic[@"taskId"]];
////
////            self->_playerVC.backVideoPath = ^(NSString * _Nonnull videoStr, NSString * _Nonnull httpStr) {
////                [dic setValue:videoStr forKey:@"video"];
////                [dic setValue:httpStr forKey:@"videoStr"];
////
////                [weakSelf uploadVideoPathWithVideoDic:dic];
////            };
////
////            [self.navigationController pushViewController:self->_playerVC animated:YES];
////
////                                                             }];
//        UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"查看编辑" style:UIAlertActionStyleDefault
//                                                             handler:^(UIAlertAction * action) {
//                                                                 //响应事件
//
//            SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
//            playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//
//            playerVC.urlStr = [NSString stringWithFormat:@"%@",dic[@"videoStr"]];
//            [self presentViewController:playerVC animated:YES completion:nil];
//                                                             }];
//        [alert addAction:saveAction];
//        [alert addAction:cancelAction];
//        [alert addAction:deleteAction];
//
//        [self presentViewController:alert animated:YES completion:nil];

    }
    
}

-(void)uploadVideoPathWithVideoDic:(NSMutableDictionary *)dic{
    float videoX = 0;
    float videoY = 0;
    float biX = 0;
    float biy = 0;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        videoX = [[dic nilObjectForKey:@"y"] floatValue];
        videoY = [[dic nilObjectForKey:@"x"] floatValue];
        
        biX = (([[dic nilObjectForKey:@"y"] floatValue]+70)/self.view.width)*100;
        biy = ((self.view.height -[[dic nilObjectForKey:@"x"] floatValue]+70)/(self.view.height - 70) )*100;
    }else if (orientation == UIInterfaceOrientationLandscapeLeft){
        
        videoX = self.view.width - [[dic nilObjectForKey:@"y"] floatValue]-70;
        videoY = [[dic nilObjectForKey:@"x"] floatValue];
        biX = (videoX/self.view.width)*100;
        biy = ((videoY -70)/(self.view.height - 70) )*100;
    }

    
    NSDictionary *dict = @{
        @"floorId":[dic nilObjectForKey:@"floorId"],
        @"path":[dic nilObjectForKey:@"video"],
        @"suffix":@"mp4",
        @"size":dic[@"Size"],
        @"duration":dic[@"Duration"],
        @"x":[NSString stringWithFormat:@"%.3f",biX],
        @"y":[NSString stringWithFormat:@"%.3f",biy]
    };
    [SYRequestAPI postDataFromURLScheme:@"resource/MyResourceService.svc/SaveVideo" parameterDictionary:dict success:^(id responseObject) {
        
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.drawView.backImage.image = image;
    
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        [weakSelf.drawView showSettingBoard];
    }];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        [weakSelf.drawView showSettingBoard];
    }];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    NSMutableArray *marray = [NSMutableArray array];
    
    for(int i=0;i<assets.count;i++){
        
        ALAsset *asset = assets[i];
        
        UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        
        [marray addObject:image];
        
    }
    self.drawView.backImage.image = [marray firstObject];
    
//    [self updataImageRequestWithImage:[marray firstObject]];

    
}
#pragma mark - HBDrawingBoardDelegate
- (void)drawBoard:(HBDrawingBoard *)drawView action:(HBDrawingShapeType)action{
    __weak typeof(self) weakSelf = self;
    switch (action) {
        case HBDrawingShapeLine:
        {

            self.drawView.shapType = 1;

//            [self.drawView showSettingBoard];

        }

            break;
        case HBDrawingShapeEllipse:
        {
            self.drawView.shapType = 2;

//            [self.drawView showSettingBoard];
        }
            break;
        case HBDrawingShapeRect:
        {
            self.drawView.shapType = 3;

//            [self.drawView showSettingBoard];
        }
            break;

        case HBDrawingSetTypeAlbum:
        {
            __weak typeof(self) weakSelf = self;

            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"选择图片" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 选择图片
                ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc]init];
                picker.maximumNumberOfSelection = 1;
                picker.assetsFilter = [ALAssetsFilter allAssets];
                picker.showEmptyGroups = NO;
                picker.delegate = self;
                [self presentViewController:picker animated:YES completion:nil];
            }];
            
            UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"线上" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                SYChooseImageViewController *VC = [[SYChooseImageViewController alloc]init];
                VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
                
                VC.chooseImage = ^(NSString * _Nonnull imageUrl) {
                    
                    [weakSelf.drawView.backImage sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil];;

                };
                [self presentViewController:VC animated:YES completion:nil];


            }];
            
            [alertController addAction:okAction];
            [alertController addAction:setAction];
            
            [self presentViewController:alertController animated:YES completion:nil];

        }
            break;
            
            
        default:
            break;
    }
    
}
//上传图片
-(void)updataImageRequestWithImage:(UIImage *)image{
    

//    http://image.31waiyu.com/HttpUpload/HttpFileUpload.ashx
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:image];

    [NSObject executeRunloop:^{
            //    获取图片
            
            
            NSMutableArray *dataImageArr = [NSMutableArray array];
        
            dataImageArr = [UIImage saveImageCommentImageArr:arr namePhoto:@"weike"];
        
            NSString *fileNames = @"";
            
            for (NSInteger i = 0; i<dataImageArr.count; i++) { {
                if (i == 0) {
                    fileNames = @"weike_userHeader_0.png";
                } else {
                    fileNames = [NSString stringWithFormat:@"%@,AddWorks_userHeader_%ld.png",fileNames,i];
                }
            }
            }
            
            NSDictionary *dict = @{@"fileNames":fileNames};
            [MBProgressHUD mj_showMessage:@"正在上传" toView:self.view];
            [SYRequestAPI uploadWithUrl:@"http://image.31waiyu.com/HttpUpload/HttpFileUpload.ashx" parameters:dict images:dataImageArr name:@"FileNames" fileName:@"weike" progress:@"" success:^(id responseObject) {
                NSArray *pathArr = responseObject[@"data"];
                NSDictionary *data = pathArr[0];
                
                self.imgaePath = [data nilObjectForKey:@"RelativePath"];
                
                [self saveTuYaImageRequestWithImagePath:self.imgaePath];
                
            } fail:^(NSError *error) {
//                [MBProgressHUD mj_hideHUD];
                [MBProgressHUD zr_showError:error.domain];
            }];
    } afterDelay:0.3];
}
// 保存微课
-(void)saveWeiKeRequestWithImagePath:(NSString *)imagePath{
    if (self.sortId.length <= 0 || self.sortId == nil) {
        self.sortId = @"0";
    }
    
    if (self.resourceId.length <= 0 || self.resourceId == nil) {
        self.resourceId = @"0";
    }
    
    NSDictionary *dict = @{
        
        @"resourceId":self.resourceId,
        @"sortId":self.sortId,
        @"sort":@"0",
        @"groupId":@"0",
        @"campusId":@"0",
        @"title":self.titileName,
        @"path":imagePath,
        @"width":[NSString stringWithFormat:@"%.2f",kScreen_WIDTH],
        @"height":[NSString stringWithFormat:@"%.2f",(kScreen_HEIGHT -70)]
    };
    [SYRequestAPI postDataFromURLScheme:@"resource/MyResourceService.svc/SaveResourceNew" parameterDictionary:dict success:^(id responseObject) {
        NSDictionary *dataDic = responseObject[@"data"];
        self.WeiDIc = dataDic;
        self.resourceId = [NSString stringWithFormat:@"%@",[self.WeiDIc nilObjectForKey:@"id"]];
        
        if (imagePath.length > 0) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"huaBan" object:nil userInfo:nil];
            [self dismissViewControllerAnimated:YES completion:^{
                
                
            }];
        }
        
    } fail:^(NSError *error) {
        
    }];
    
}
// 保存涂鸦照片
-(void)saveTuYaImageRequestWithImagePath:(NSString *)imagePath{
    
    NSArray *floorList = self.WeiDIc[@"listFloor"];
    NSDictionary *floorDic = floorList[0];
    NSDictionary *dict = @{
        
        @"floorId":[NSString stringWithFormat:@"%@",[floorDic nilObjectForKey:@"id"]],
        @"path":imagePath,
        @"width":[NSString stringWithFormat:@"%.2f",kScreen_WIDTH],
        @"height":[NSString stringWithFormat:@"%.2f",(kScreen_HEIGHT -70)]
    };
    [SYRequestAPI postDataFromURLScheme:@"resource/MyResourceService.svc/SaveDoodlingFile" parameterDictionary:dict success:^(id responseObject) {
        
        [self saveWeiKeRequestWithImagePath:imagePath];
        
        
    } fail:^(NSError *error) {
        
    }];
    
}
- (IBAction)backBtnClick:(id)sender {
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否确定退出！" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    [alert addAction:cancel];
    [alert addAction:confirm];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)drawBoard:(HBDrawingBoard *)drawView drawingStatus:(HBDrawingStatus)drawingStatus model:(HBDrawModel *)model{
    
//    NSLog(@"%@",model.keyValues);
}
- (HBDrawingBoard *)drawView
{
    if (!_drawView) {


        _drawView = [[HBDrawingBoard alloc] initWithFrame:CGRectMake(0, 80, kScreen_WIDTH, kScreen_HEIGHT - 80)];
        _drawView.delegate = self;
        
    }
    return _drawView;
}

@end
